<?php

namespace Lib\Core;

class Remote {

    public static $globalParams = array();

    public function __get($name) {
        $config = new \Config\Remote();
        $config = $config->$name;
        $request = new RequestServer($config);
        return $request;
    }

    public static function setGlobalParams($key, $val) {
        self::$globalParams[$key] = $val;
    }
}

class RequestServer {

    private $__config;
    private $__url;

    public function __construct($config) {
        $this->__config = $config;
    }

    private function __setUrl($controller) {
        $this->__url = $this->__config['Address'] . '/' . $this->__config['AppName'] . '/' . $controller;
    }

    private function __request($fun, $params) {
        $dataParms = empty($params[0]) ? '' : json_encode($params[0]);
        $postData = array(
            'data' => $dataParms
        );
        $postData['global'] = json_encode(Remote::$globalParams);
        $url = $this->__url . '/' . $fun;
        $result = $this->request($url, $postData, 5, null, null, 0);
        $data = $this->__parseResult($result);
        return $data;
    }

    private function request($url, $postData = null, $timeout = 5, $header = array(), $curlProcess = null, $isHeader = 0) {
        $ch = curl_init($url);
        if (!$curlProcess) {
            $curlProcess = function(){};
        }
        if ($curlProcess) {
            $curlProcess($ch);
        }
        if ($postData) {
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData));
        } else {
            curl_setopt($ch, CURLOPT_POST, 0);
        }
        if ($header) {
            curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        }
        curl_setopt($ch, CURLOPT_HEADER, $isHeader);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        if ($timeout) {
            curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
        }
        $return = curl_exec($ch);
        return $return;
    }

    private function __parseResult($result) {
        if ($result === false) {
            throw new \Exception('网络错误');
        }
        return json_decode($result, true);
    }

    public function __get($name) {
        $this->__setUrl($name);
        return $this;
    }

    public function __call($fun, $params) {
        return $this->__request($fun, $params);
    }
}
